import { showSuccessToast } from 'vant';
import { onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { deserialize } from '@/plugins/reflect-metadata';
import type { ListState } from '@/types';
import camel2snake from '@/utils/camel2snake';
import convertQuery from '@/utils/convertQuery';
import pathReplace from '@/utils/pathReplace';

import { clearUserBalance, getUserList, updateUserStatus } from '../api';
import { UserLoginStatus } from '../const';
import UserItem, { UserStatusConfig } from '../models/UserItem';
import UserList, { UserQuery } from '../models/UserList';

const useUserList = () => {
  const route = useRoute();
  const router = useRouter();
  const { query } = route;

  const params = ref<UserQuery>(new UserQuery());
  const state = ref<ListState<UserItem>>({
    data: [],
    loading: false,
    total: 0,
  });

  watch(
    () => params.value.params,
    () => {
      pathReplace(
        router,
        route,
        camel2snake({
          realName: params.value.realName,
          userName: params.value.userName,
          status: `${params.value.status}`,
        }),
      );
    },
    { immediate: true },
  );

  const fetchData = async () => {
    try {
      state.value.loading = true;
      const { data } = await getUserList(params.value);
      const resultData = deserialize(data, UserList);
      state.value.data = resultData.items;
      state.value.total = resultData.total;
    } catch (error) {
      //
    } finally {
      state.value.loading = false;
    }
  };

  const config = ref<UserStatusConfig>(new UserStatusConfig());
  const handleUpdate = async (item: UserItem) => {
    try {
      state.value.loading = true;
      config.value.status = Number(item.status) === UserLoginStatus.正常
        ? UserLoginStatus.禁用 : UserLoginStatus.正常;
      config.value.userId = item.userId;
      const { data } = await updateUserStatus(config.value);
      showSuccessToast(data.msg || '操作成功');
    } catch (error) {
      //
    } finally {
      state.value.loading = false;
    }
  };

  const handleClear = async (item: UserItem) => {
    try {
      state.value.loading = true;
      config.value.userId = item.userId;
      const { data } = await clearUserBalance(config.value);
      showSuccessToast(data.msg || '操作成功');
    } catch (error) {
      //
    } finally {
      state.value.loading = false;
    }
  };

  onMounted(async () => {
    params.value = deserialize(
      convertQuery(query, ['real_name', 'user_name', 'status']),
      UserQuery,
    );
    await fetchData();
  });

  return {
    params,
    state,
    fetchData,
    handleUpdate,
    handleClear,
  };
};

export default useUserList;
